/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.service.singleton {
	import com.googlecode.milib.MILibMain;
	import com.googlecode.milib.base.MLBroadcastClass;

	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.getTimer;

	/**
	 * @author Marek Brun
	 */
	public class FPSMonitor extends MLBroadcastClass {

		public function get event_Updated():String {
			return 'Updated';
		}
		
		private var lastTime:int;		private var countFrames:uint=0;		private var countSeconds:uint=0;
		private var stage:Stage;
		private var lastCountFrames:uint;
		private static var instance:FPSMonitor;
		
		public function FPSMonitor(access:Private) {
			MILibMain.getInstance().getRoot().addEventListener(Event.ENTER_FRAME, onStageEnterFrame, false, 0, true);
			lastTime=getTimer();
			stage=MILibMain.getInstance().getStage();
		}
		
		private function doEnterFrame():void {
			countFrames++;
			if(getTimer()-lastTime>1000) {
				lastCountFrames=countFrames;
				countFrames=0;
				lastTime=getTimer();
				countSeconds++;
				broadcastEvent(event_Updated);
			}
		}
		
		public function getTextData():String {
			return 'FPS: '+getCurrentFPS()+'/'+stage.frameRate;
		}
		
		public function getCurrentFPS():uint {
			return lastCountFrames;
		}
		
		public function getSecondsCounted():uint {
			return countSeconds;
		}
		
		public function getMax():Number {
			return stage.frameRate;
		}
		
		public static function getInstance():FPSMonitor {
			if(instance) { return instance; }
			else{ instance=new FPSMonitor(null); return instance; }
		}
		
//********************************************************************************************
//		events for MLDBGFPSObservator
//********************************************************************************************
		protected function onStageEnterFrame(event:Event):void {
			doEnterFrame();
		}
	}
}
internal class Private {}
